package com.service;

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Slf4j
@org.springframework.stereotype.Service
public class Service {

    @Retry(name = "default")
    @RateLimiter(name = "default")
    @Bulkhead(name = "default",type = Bulkhead.Type.THREADPOOL) // when @Bulkhead(name) is equal then  use the same threadpool
    @CircuitBreaker(name = "default")
    @TimeLimiter(name = "backendA", fallbackMethod = "fallback")
    public CompletableFuture<String> completableFuture(long waittime){
      return   CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(waittime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "timeout";
        });
    }
    public CompletableFuture<String> fallback(long waittime, Throwable throwable) {
        if (throwable != null) {
            log.error("===============msg:{}", throwable.getMessage());
        }
        return CompletableFuture.completedFuture("recover from error...");
    }
}
